﻿using System;

namespace Lib.Helper
{

        public enum MidpointRounding
        {
            ToEven,
            AwayFromZero
        }


    public static class DecimalExtensions
    {

        public static decimal Round(this decimal d, MidpointRounding mode)
        {

            return d.Round(0, mode);

        }



        /// <summary>

        /// Rounds using arithmetic (5 rounds up) symmetrical (up is away from zero) rounding

        /// </summary>

        /// <param name="d">A Decimal number to be rounded.</param>

        /// <param name="decimals">The number of significant fractional digits (precision) in the return value.</param>

        /// <returns>The number nearest d with precision equal to decimals. If d is halfway between two numbers, then the nearest whole number away from zero is returned.</returns>

        public static decimal Round(this decimal d, int decimals, MidpointRounding mode)
        {

            if (mode == MidpointRounding.ToEven)
            {

                return decimal.Round(d, decimals);

            }

            else
            {

                decimal factor = Convert.ToDecimal(Math.Pow(10, decimals));

                int sign = Math.Sign(d);

                return Decimal.Truncate(d * factor + 0.5m * sign) / factor;

            }

        }

    }

}
